#ifndef __LOG_HPP__
#define __LOG_HPP__
#pragma once
#include <iostream>
#include <string>
#include <mutex>
#include <filesystem> //c++17创建文件目录
#include <fstream>    //文件操作
#include <sys/types.h>
#include <unistd.h>
#define crlf "\r\n"

namespace LogModule
{
    class RefreshStrategy
    {
    public:
        ~RefreshStrategy() = default;
        virtual void RefreshLog(std::string message) = 0;
    };

    class DisplayStrategy : public RefreshStrategy
    {
    public:
        void RefreshLog(std::string message)
        {
            _lock.lock();
            std::cout << message << crlf;
            _lock.unlock();
        }

    private:
        std::mutex _lock;
    };

    const std::string DefLoad = "./log";
    const std::string DefName = "my.log";

    class FileStrategy : public RefreshStrategy
    {
    public:
        FileStrategy(const std::string name = DefName, const std::string load = DefLoad)
            : _name(name), _load(load)
        {
            _lock.lock();
            if (std::filesystem::exists(_load))
            {
                return;
            }
            else
            {
                std::cout << "路径不存在，创建路径！" << crlf;
                std::filesystem::create_directories(_load);
            }
            _lock.unlock();
        }

        void RefreshLog(std::string message)
        {
            _lock.lock();
            std::string filename = _load + (_load.back() == '/' ? "" : "/") + _name;
            std::ofstream out(filename, std::ios::app);
            if (!out.is_open())
            {
                std::cout << "文件打开失败！" << crlf;
                return;
            }
            else
            {
                out << message << crlf;
                out.close();
            }
            _lock.unlock();
        }

        ~FileStrategy()
        {
        }

    private:
        std::string _name;
        std::string _load;
        std::mutex _lock;
    };

    enum struct LogLevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };

    const static std::string level[5] = {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
    std::string IndToLevel(const int ind)
    {
        return level[ind];
    }

    std::string getCurTime()
    {
        char cur_time[128];
        time_t timestamp = time(0);
        std::tm *_tm = std::localtime(&timestamp);
        snprintf(cur_time, sizeof(cur_time),
                 "%4d-%02d-%02d %02d:%02d:%02d",
                 _tm->tm_year + 1900, _tm->tm_mon + 1,
                 _tm->tm_mday, _tm->tm_hour, _tm->tm_min, _tm->tm_sec);
        return cur_time;
    }

    class Log
    {
    public:
        Log()
        {
            // 默认向显示器打印日志
            _log_strategy = std::make_unique<DisplayStrategy>();
        }

        void shiftToFile()
        {
            _log_strategy = std::make_unique<FileStrategy>();
        }

        void shiftToDisplay()
        {
            _log_strategy = std::make_unique<DisplayStrategy>();
        }

        /*                std::stringstream ss;
            ss << "[" << _curr_time << "] "
               << "[" << Level2Str(_level) << "] "
               << "[" << _pid << "] "
               << "[" << _src_name << "] "
               << "[" << _line_number << "] "
               << "- ";
            _loginfo = ss.str();*/
        class LogMessage
        {
        public:
            LogMessage(const int level, const std::string src_file, size_t line, Log &log)
                : _cur_time(getCurTime()), _level(IndToLevel(level)), _pid(getpid()), _src_file(src_file), _line(line), _log(log)
            {
                std::stringstream ss;
                ss << "[" << _cur_time << "] "
                   << "[" << _level << "] "
                   << "[" << _pid << "] "
                   << "[" << _src_file << "] "
                   << "[" << _line << "] "
                   << "- ";
                _total_message = ss.str();
            }

            template <class T>
            LogMessage &operator<<(T message)
            {
                std::stringstream ss;
                ss << message;
                _total_message += ss.str();
                return *this;
            }

            ~LogMessage()
            {
                if (_log._log_strategy)
                    _log._log_strategy->RefreshLog(_total_message);
            }

        private:
            std::string _cur_time;
            std::string _level;
            pid_t _pid;
            std::string _src_file;
            size_t _line;
            std::string _total_message;
            Log &_log;
        };

        LogMessage operator()(const int level, const std::string file, size_t line)
        {
            return LogMessage(level, file, line, *this);
        }

    private:
        std::unique_ptr<RefreshStrategy> _log_strategy;
    };

    Log logger;

    #define LOG(level) logger(level, __FILE__, __LINE__)
    #define Enable_Console_Log_strategy() logger.shiftToDisplay();
    #define Enable_File_Log_Strategy() logger.shiftToFile();
}

#endif

